from flask import Flask, request
from flask.json.provider import DefaultJSONProvider
from flask_cors import CORS
from .extensions.extensions import db, jwt
from .config.settings import Config
from .utils.init_db import init_database

class CustomJSONProvider(DefaultJSONProvider):
    """自定义JSON提供器"""
    def default(self, obj):
        from datetime import datetime
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        return super().default(obj)

    def dumps(self, obj, **kwargs):
        # 确保中文不会被转义
        kwargs.setdefault('ensure_ascii', False)
        return super().dumps(obj, **kwargs)

    def loads(self, s: str | bytes, **kwargs):
        # 确保正确处理中文输入
        import json
        if isinstance(s, bytes):
            try:
                s = s.decode('utf-8')
            except UnicodeDecodeError:
                encoding = request.content_type.split('charset=')[-1] if request.content_type and 'charset=' in request.content_type else 'latin-1'
                s = s.decode(encoding, errors='replace')
        return json.loads(s, **kwargs)

def create_app(enable_auth=True):
    """
    创建Flask应用
    :param enable_auth: 是否启用认证，默认关闭
    :return: Flask应用实例
    """
    app = Flask(__name__)
    app.config.from_object(Config)
    
    # 设置JSON编码
    app.config['JSON_AS_ASCII'] = False
    app.config['JSONIFY_MIMETYPE'] = "application/json; charset=utf-8"
    app.json_provider_class = CustomJSONProvider
    app.json = CustomJSONProvider(app)
    

    # 初始化扩展
    CORS(app)
    db.init_app(app)
    
    # 根据参数决定是否启用JWT认证
    if enable_auth:
        jwt.init_app(app)
    else:
        app.config['JWT_TOKEN_LOCATION'] = []
        app.config['JWT_COOKIE_CSRF_PROTECT'] = False
    
    # 注册蓝图
    from .controllers.auth import auth_bp
    from .controllers.user import user_bp
    from .controllers.role import role_bp
    from .controllers.permission import permission_bp
    from .controllers.user_role import user_role_bp
    from .controllers.role_permission import role_permission_bp
    
    app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')
    app.register_blueprint(user_bp, url_prefix='/api/v1/users')
    app.register_blueprint(role_bp, url_prefix='/api/v1/roles')
    app.register_blueprint(permission_bp, url_prefix='/api/v1/permissions')
    app.register_blueprint(user_role_bp, url_prefix='/api/v1/user-roles')
    app.register_blueprint(role_permission_bp, url_prefix='/api/v1/role-permissions')
    
    with app.app_context():
        # 初始化数据库
        init_database()
    
    return app 